package com.gzy.rpsm_property.controller;

import com.gzy.rpsm_property.pojo.*;
import com.gzy.rpsm_property.service.MessageService;
import com.gzy.rpsm_property.service.UserService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.constraints.NotBlank;
import java.sql.Date;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/messages")
@Api(tags = "信息")
public class MessageController {

    @Autowired
    private MessageService messageService;
    @Autowired
    private UserService userService;
    private static final Logger logger = LoggerFactory.getLogger(MessageController.class);

    @GetMapping("/with-user-details")
    @ApiOperation(value = "获取所有留言信息，并携带用户信息")
    public List<Ms> getAllMessagesWithUserDetails() {
        try {
            logger.info("Request received to get all messages with user details");
            return userService.getAllMessagesWithUserDetails();
        } catch (Exception e) {
            logger.error("Error occurred while fetching messages with user details", e);
            throw new RuntimeException("获取留言信息失败", e);
        }
    }

    @GetMapping("/messages/username")
    @ApiOperation(value = "根据用户名获取用户及其留言信息")
    public List<Ms> getUserAndMessagesByUsername(@RequestParam @NotBlank(message = "用户名不能为空") String username) {
        try {
            logger.info("Request received to get messages for username: {}", username);
            return messageService.getUserAndMessagesByUsername(username);
        } catch (Exception e) {
            logger.error("Error occurred while fetching messages for username: {}", username, e);
            throw new RuntimeException("获取留言信息失败", e);
        }
    }

    @PostMapping("/send-message")
    @ApiOperation(value = "发送留言")
    public ResponseEntity<String> sendMessage(
            @RequestParam(required = true) int userId,
            @RequestParam(required = true) String content,
            @RequestParam(required = true) String title) {
        try {
            messageService.sendMessage(userId, content, title);
            return new ResponseEntity<>("Message sent successfully", HttpStatus.OK);
        } catch (Exception e) {
            // 记录日志
            e.printStackTrace();
            return new ResponseEntity<>("Failed to send message: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping("/{messageId}")
    @ApiOperation(value = "修改留言", notes = "根据留言ID更新留言内容和标题")
    @ApiResponses({
            @ApiResponse(code = 200, message = "留言更新成功"),
            @ApiResponse(code = 404, message = "留言未找到")
    })
    public ResponseEntity<ResponsePojo<Void>> updateMessage(
            @PathVariable int messageId,
            @RequestParam String messageContent,
            @RequestParam String messageTitle) {
        try {
            messageService.updateMessage(messageId, messageContent, messageTitle);
            return ResponseEntity.ok(ResponsePojo.success(null));
        } catch (Exception e) {
            // 处理异常，例如记录日志或抛出自定义异常
            return ResponseEntity.badRequest().body(ResponsePojo.fail(null, "留言未找到或更新失败"));
        }
    }

    @PostMapping("/{messageId}/replies")
    @ApiOperation(value = "回复留言", notes = "根据留言ID回复留言内容和标题")
    public ResponseEntity<String> replyToMessage(
            @PathVariable String messageId,
            @RequestParam String replyContent,
            @RequestParam String replyTitle,
            @RequestParam String replyUserName) {
        try {
            messageService.replyToMessage(messageId, replyContent, replyTitle, replyUserName);
            return new ResponseEntity<>("Reply sent successfully", HttpStatus.OK);
        } catch (Exception e) {
            // 记录日志
            e.printStackTrace();
            return new ResponseEntity<>("Failed to send reply: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

//    @PostMapping("/message/{messageId}")
//    public ResponseEntity<String> addReply(@PathVariable String messageId, @RequestBody Reply reply) {
//        try {
//            reply.setMessageId(Integer.parseInt(messageId)); // 设置 reply 的 messageId
//            reply.setReplyTime(Date.valueOf(LocalDate.now())); // 设置回复时间
//            messageService.addReply(reply);
//            return new ResponseEntity<>("Reply added successfully", HttpStatus.OK);
//        } catch (Exception e) {
//            // 记录日志
//            e.printStackTrace();
//            return new ResponseEntity<>("Failed to add reply: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
//        }
//    }


    @GetMapping("/{messageId}/replies")
    @ApiOperation(value = "获取留言的所有回复", notes = "根据留言ID获取所有回复")
    public ResponseEntity<List<Reply>> getRepliesByMessageId(@PathVariable int messageId) {
        try {
            logger.info("Request received to get replies for message ID: {}", messageId);
            List<Reply> replies = messageService.getRepliesByMessageId(messageId);
            if (replies == null || replies.isEmpty()) {
                logger.warn("No replies found for message ID: {}", messageId);
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity<>(replies, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("Error occurred while fetching replies for message ID: {}", messageId, e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
